package com.apexedu.portal.controller;

import com.apexedu.framework.dao.BaseDao;
import com.apexedu.framework.util.DBUtil;
import com.apexedu.framework.util.SeqFactory;
import com.apexedu.portal.entity.TSchedule;
import com.apexedu.util.DateUtil;
import com.apexedu.util.StringUtil;
import com.apexedu.util.json.JsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.List;

/**
 * 假期安排
 * Created by ly on 2015/5/26.
 */
@Controller
public class HolidayController extends BaseController {
    @Resource
    private BaseDao baseDao;

    /**
     * @return
     */
    @RequestMapping(value = "/h/i", method = RequestMethod.GET)
    public String init(HttpServletRequest request, ModelMap map) {
        String nd = request.getParameter("nd");
        if (StringUtil.isBlank(nd)) {
            Calendar cal = Calendar.getInstance();
            nd = cal.get(Calendar.YEAR) + "";
        }


        map.put("nd", nd);
        map.put("ksrq", nd + "-01-01");
        map.put("jsrq", nd + "2015-12-31");
        return "portal/holiday/init";
    }

    @RequestMapping(value = "/h/hs", method = RequestMethod.GET)
    @ResponseBody
    public String getHolidays(HttpServletRequest request) {
        String nd = request.getParameter("nd");
        if (StringUtil.isBlank(nd)) {
            Calendar cal = Calendar.getInstance();
            nd = cal.get(Calendar.YEAR) + "";
        }
        List<TSchedule> list = DBUtil.queryAllBeanList("select * from t_schedule where to_char(day,'yyyy')=? order by day", TSchedule.class, nd);
        return JsonUtil.getJSONString(list);
    }

    @RequestMapping(value = "/h/s", method = RequestMethod.POST)
    @ResponseBody
    public String saveHolidays(HttpServletRequest request) throws Exception {
        String day = request.getParameter("day");
        if (StringUtils.isNotBlank(day)) {
            if (DBUtil.count(" from T_Schedule where to_char(day,'yyyy-mm-dd')=?", day) == 0) {
                TSchedule schedule = new TSchedule();
                schedule.setWid(SeqFactory.getNewSequenceAlone());
                schedule.setDay(DateUtil.parseDate(day, DateUtil.PATTERN_DATE));
                baseDao.save(schedule);
                return "true";
            } else {
                DBUtil.executeSQL("delete from T_Schedule where to_char(day,'yyyy-mm-dd')=?", day);
                return "true";
            }
        }
        return "false";
    }
}
